<template>
  <div>
    <n-grid cols="5" x-gap="20">
      <n-gi>
        <div class="theme_box" style="padding: 20px">
          <n-thing>
            <template #header>
              <span>商品类别</span>
            </template>
            <template #header-extra>
              <n-button size="small" strong secondary @click="onAddCategory">
                <template #icon>
                  <a-icon name="Add"></a-icon>
                </template>
              </n-button>
            </template>
            <vue-draggable v-model="categoryList" item-key="index" animation="100" @end="onCategorySort">
              <template #item="{ element }">
                <n-space justify="space-between" class="category_item" @click="activedCate = element">
                  <n-radio :checked="activedCate.id == element.id" :value="element.id">
                    {{ element.cateName }}
                  </n-radio>
                  <span>
                    <n-button quaternary size="tiny" @click="onEditCategory(element)">
                      <template #icon>
                        <a-icon name="Edit"></a-icon>
                      </template>
                    </n-button>
                    <n-button quaternary size="tiny" @click.stop="onDeleteCategory(element)">
                      <template #icon>
                        <a-icon name="Delete"></a-icon>
                      </template>
                    </n-button>
                  </span>
                </n-space>
              </template>
            </vue-draggable>
          </n-thing>
        </div>
      </n-gi>
      <n-gi span="4">
        <div class="theme_box">
          <ocean :use="template"></ocean>
        </div>
      </n-gi>
    </n-grid>
    <ocean :use="dialog" style="width: 400px"></ocean>
    <ocean :use="drawer"></ocean>
    <ocean :use="preview"></ocean>
  </div>
</template>
<script lang="tsx" setup>
import { ref, watch } from 'vue';
import vueDraggable from 'vuedraggable';
import { GoodsAPI } from '@/app/api';
import { useDialog, useTableTemplate, useDrawer } from '@/ocean';
import CategoryForm from './form/category.vue';
import { Warning } from '@/hooks/useTip';
import PickGoods from './components/pickGoods.vue';
import Preview from './components/preview.vue';
import { useMessage } from 'naive-ui';

type Column = {
  carbs: '52.1';
  cateName: null;
  childIds: null;
  cover: null;
  createTime: '2022-08-27 22:15:47';
  dietaryFiber: '3.5';
  disCount: 0.4;
  fat: '12.5';
  foodTypes: '7';
  goodsDesc: '一道好菜，精彩之处不光在于最后被人品尝，还在制作过程中。这就是为什么美食视频喜欢重点拍摄厨师做菜的片段。\n很多外卖商家会将制作方法在菜品描述中详细写出来，一方面是为了让顾客对菜品更放心，另一方面也能引发他们对口味的期待感';
  goodsName: '油泼面';
  goodsOption: '1';
  id: 10;
  isCombo: 2;
  kcal: '300';
  likeCount: 99;
  limitNum: 2;
  monthSales: 3000;
  originPrice: 50;
  praiseRate: 0;
  protein: '27.8';
  salt: '1.7';
  sellPrice: 20;
  status: 1;
  storeName: null;
  totalSales: 9999;
  updateTime: '2022-08-27 22:15:47';
};

let message = useMessage();

let dialog = useDialog('添加类别', CategoryForm);
dialog.button('确认', { type: 'primary' }).click(() => {
  let { submit } = dialog.getRef();
  submit().then(() => {
    queryCategoryList();
    dialog.close();
  });
});
dialog.button('取消').click(() => {
  dialog.close();
});

let categoryList = ref([]);
let activedCate = ref<any>({});

let queryCategoryList = () => {
  return GoodsAPI.queryCategoryList().then(res => {
    categoryList.value = res.data.sort((a, b) => a.sort - b.sort);
  });
};

let queryAllGoodsByCate = () => {
  let cateId = activedCate.value.id || '';
  return GoodsAPI.queryAllGoodsByCate({ cateId }).then(res => {
    template.table.setData(res.data || []);
  });
};

let delGoodsFromCate = row => {
  Warning('是否下架商品：' + row.goodsName).then(({ message }) => {
    return GoodsAPI.delGoodsFromCate({ cateId: activedCate.value.id, goodsId: row.id }).then(() => {
      template.query();
      message.success('下架成功');
    });
  });
};

const onCategorySort = () => {
  let sortData = categoryList.value.map((o, i) => ({ id: o.id, sort: i }));
  GoodsAPI.sortCategory(sortData);
};

const onAddCategory = () => {
  dialog.setTitle('添加类别').open();
};

const onEditCategory = cate => {
  dialog.setTitle('编辑类别').open({ category: cate });
};

const onDeleteCategory = cate => {
  Warning('是否删除' + cate.cateName).then(({ message }) => {
    GoodsAPI.deleteCategory({ goodsCateId: cate.id }).then(() => {
      queryCategoryList();
      message.success('删除成功');
    });
  });
};

let template = useTableTemplate<Column>('分类商品', {
  query: () => queryAllGoodsByCate()
});

template.pagination = false as any;

template.form.item('商品名称', 'goodsName').input();
// template.form.item('售价', 'sellPrice').input();

template.button('添加分类相关商品', { type: 'primary' }).click(() => {
  drawer.open({ category: activedCate.value, onUpdate: () => template.query() });
});
template.button('小程序效果预览').click(() => {
  preview.open();
});

template.table.column('商品图片', 'cover').image();
template.table.column('商品名称', 'goodsName');
template.table.column('规格', 'goodsOption');
template.table.column('售价', 'sellPrice');
template.table.column('原价', 'originPrice');
template.table.column('创建时间', 'createTime');
template.table.define({
  title: '操作',
  render: row => <n-button on-click={() => delGoodsFromCate(row)}>下架</n-button>
});

let drawer = useDrawer('添加分类商品', PickGoods, { size: 'medium' });
drawer.button('取消').click(() => {
  drawer.close();
});

queryCategoryList().then(() => {
  if (categoryList.value.length) {
    activedCate.value = categoryList.value[0];
  }
});

let preview = useDrawer('小程序效果预览', Preview, { size: 'small' });
preview.button('确认', { type: 'primary' }).click(() => preview.close());

watch(
  () => activedCate.value,
  () => template.query()
);
</script>
<style lang="scss" scoped>
.category_item {
  padding: 5px;
  margin-bottom: 10px;
  cursor: move;

  @include themeify {
    background: theme('bg_secondary');
  }
}
</style>
